package com.cheneyjoo.servlets;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cheneyjoo.controller.SysUserController;
import com.cheneyjoo.model.SYS_USER;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Optional;

@javax.servlet.annotation.WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends javax.servlet.http.HttpServlet {
    private static final long serialVersionUID = -8232639260510821854L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        String userName = request.getParameter("name");
        System.out.println(userName);
        String password = request.getParameter("password");
        System.out.println(password);
        SysUserController suc = new SysUserController();
        SYS_USER user = suc.login(userName, password);
        if (Optional.ofNullable(user).isEmpty()) {
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("login.jsp");
            requestDispatcher.forward(request, response);
        } else {
            String encodeCookie = URLEncoder.encode(JSON.toJSONString(user),"utf-8");
            Cookie cookie = new Cookie("user", encodeCookie);
            cookie.setMaxAge(7 * 24 * 60 * 60);
            response.addCookie(cookie);

            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            response.sendRedirect(request.getContextPath() + "/ui/index.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        this.doPost(request, response);
    }
}
